import { RenderSystem } from '../systems/RenderSystem.js';
import { InputSystem } from '../systems/InputSystem.js';
import { UISystem } from '../systems/UISystem.js';
import { EntitySystem } from '../systems/EntitySystem.js';
import { AttackSystem } from '../systems/AttackSystem.js';
import { DefenseSystemManager } from '../systems/DefenseSystemManager.js';
import { VisualEffectsSystem } from '../systems/VisualEffectsSystem.js';
import { AudioSystem } from '../systems/AudioSystem.js';
import { EnhancedUISystem, UIState } from '../systems/EnhancedUISystem.js';
import { PerformanceOptimizationSystem } from '../systems/PerformanceOptimizationSystem.js';
import { GameConfig, DefenseSystemType } from '../config/GameConfig.js';
import { Missile } from '../entities/Missile.js';
import { DefenseSystem } from '../entities/DefenseSystem.js';

export class GameEngine {
    private canvas: HTMLCanvasElement;
    private ctx: CanvasRenderingContext2D;
    private isRunning: boolean = false;
    private lastFrameTime: number = 0;
    private deltaTime: number = 0;
    private frameCount: number = 0;
    private fps: number = 0;
    
    // 游戏统计追踪
    private gameStatistics = {
        missilesIntercepted: 0,
        gameStartTime: 0
    };
    
    // 自动攻击序列
    private autoAttackEnabled: boolean = true;
    private autoAttackTimer: number = 0;
    private autoAttackDelay: number = 5000; // 游戏开始5秒后自动攻击
    private currentAutoWave: number = 1;
    private waveInterval: number = 30000; // 每30秒一波
    private hasStartedAutoAttack: boolean = false;
    
    // 系统实例
    private renderSystem: RenderSystem;
    private inputSystem: InputSystem;
    private uiSystem: UISystem;
    private entitySystem: EntitySystem;
    private attackSystem: AttackSystem;
    private defenseSystemManager: DefenseSystemManager;
    
    // Stage 3 新增系统
    private visualEffectsSystem: VisualEffectsSystem;
    private audioSystem: AudioSystem;
    private enhancedUISystem: EnhancedUISystem;
    private performanceSystem: PerformanceOptimizationSystem;

    constructor() {
        // 获取画布元素
        this.canvas = document.getElementById('gameCanvas') as HTMLCanvasElement;
        if (!this.canvas) {
            throw new Error('找不到游戏画布元素');
        }

        const ctx = this.canvas.getContext('2d');
        if (!ctx) {
            throw new Error('无法获取2D渲染上下文');
        }
        this.ctx = ctx;

        // 初始化各个系统
        this.renderSystem = new RenderSystem(this.ctx);
        this.inputSystem = new InputSystem(this.canvas);
        this.uiSystem = new UISystem();
        this.entitySystem = new EntitySystem();
        this.attackSystem = new AttackSystem(this.entitySystem);
        this.defenseSystemManager = new DefenseSystemManager(this.entitySystem);
        
        // 初始化Stage 3新增系统
        this.visualEffectsSystem = new VisualEffectsSystem(this.ctx);
        this.audioSystem = new AudioSystem();
        this.enhancedUISystem = new EnhancedUISystem(this.ctx, this.canvas);
        this.performanceSystem = new PerformanceOptimizationSystem(this.canvas, this.ctx);
    }

    async init(): Promise<void> {
        console.log('🔧 正在初始化游戏引擎...');
        
        // 设置全局引用以便其他系统访问
        (globalThis as any).gameEngine = this;
        (globalThis as any).MissileClass = (await import('../entities/Missile.js')).Missile;
        (globalThis as any).InterceptorClass = (await import('../entities/Interceptor.js')).Interceptor;

        try {
            // 初始化各个系统
            await this.renderSystem.init();
            await this.inputSystem.init();
            await this.uiSystem.init();
            await this.entitySystem.init();
            await this.attackSystem.init();
            await this.defenseSystemManager.init();
            
            // 初始化Stage 3新增系统 - 无需await，都是同步初始化
            // this.visualEffectsSystem 已在构造函数中初始化
            // this.audioSystem 已在构造函数中初始化  
            // this.enhancedUISystem 已在构造函数中初始化
            // this.performanceSystem 已在构造函数中初始化

            // 设置画布基本属性
            this.setupCanvas();

            // 设置系统间的通信
            this.setupSystemCommunication();
            
            // 创建对象池（Stage 3 性能优化）
            this.setupObjectPools();
            
            // 自动部署初始防御系统
            this.setupInitialDefenses();

            console.log('✅ 游戏引擎初始化完成');
        } catch (error) {
            console.error('❌ 游戏引擎初始化失败:', error);
            throw error;
        }
    }

    start(): void {
        if (this.isRunning) {
            console.warn('⚠️ 游戏已经在运行中');
            return;
        }

        console.log('🎮 启动游戏循环');
        this.isRunning = true;
        this.lastFrameTime = performance.now();
        this.gameStatistics.gameStartTime = Date.now();
        
        // 启动游戏循环
        this.gameLoop();
    }

    stop(): void {
        console.log('⏹️ 停止游戏循环');
        this.isRunning = false;
    }

    private gameLoop = (): void => {
        if (!this.isRunning) return;

        const currentTime = performance.now();
        
        // 使用性能系统管理帧率
        const shouldRender = this.performanceSystem.update(currentTime);
        this.deltaTime = this.performanceSystem.getDeltaTime();

        // 更新FPS计数
        this.updateFPS();

        try {
            // 更新各个系统
            this.update(this.deltaTime);
            
            // 只在需要时渲染
            if (shouldRender) {
                this.render();
            }
        } catch (error) {
            console.error('❌ 游戏循环错误:', error);
            this.stop();
            return;
        }

        // 请求下一帧
        requestAnimationFrame(this.gameLoop);
    };

    private update(deltaTime: number): void {
        // 检查增强UI系统状态
        const uiState = this.enhancedUISystem.getCurrentState();
        if (uiState === UIState.GAME_PAUSED || uiState === UIState.MAIN_MENU || 
            uiState === UIState.SETTINGS || uiState === UIState.GAME_OVER) {
            // 游戏暂停或在菜单中，只更新UI系统
            this.enhancedUISystem.update(deltaTime);
            this.audioSystem.update(deltaTime);
            return;
        }

        // 更新实体系统
        this.entitySystem.update(deltaTime);
        
        // 更新攻击系统
        this.attackSystem.update(deltaTime);
        
        // 更新防御系统管理器
        this.defenseSystemManager.update(deltaTime);
        
        // 更新输入系统
        this.inputSystem.update(deltaTime);
        
        // 更新UI系统
        this.uiSystem.update(deltaTime);
        
        // 更新Stage 3新增系统
        this.visualEffectsSystem.update(deltaTime);
        this.audioSystem.update(deltaTime);
        this.enhancedUISystem.update(deltaTime);
        
        // 更新自动攻击序列
        this.updateAutoAttack(deltaTime);
        
        // 更新游戏状态显示
        this.updateGameStatusDisplay();
    }

    private render(): void {
        // 检查UI状态，决定渲染内容
        const uiState = this.enhancedUISystem.getCurrentState();
        
        if (uiState === UIState.MAIN_MENU || uiState === UIState.SETTINGS || 
            uiState === UIState.HELP || uiState === UIState.GAME_OVER || uiState === UIState.VICTORY) {
            // 菜单状态，只渲染增强UI
            this.enhancedUISystem.render();
            return;
        }

        // 游戏状态渲染
        // 清空画布
        this.renderSystem.clear();
        
        // 渲染背景
        this.renderSystem.renderBackground();
        
        // 渲染所有实体
        this.entitySystem.render(this.renderSystem);
        
        // 渲染视觉效果（粒子系统）
        this.visualEffectsSystem.render();
        
        // 渲染增强UI（游戏中的UI）
        if (uiState === UIState.GAME_PLAYING || uiState === UIState.GAME_PAUSED) {
            this.enhancedUISystem.render();
        }
        
        // 渲染调试信息
        if (GameConfig.DEBUG.ENABLED) {
            this.renderDebugInfo();
        }
    }

    private setupCanvas(): void {
        // 设置画布尺寸
        this.canvas.width = GameConfig.CANVAS_WIDTH;
        this.canvas.height = GameConfig.CANVAS_HEIGHT;
        
        // 设置默认渲染样式
        this.ctx.imageSmoothingEnabled = true;
        this.ctx.textAlign = 'left';
        this.ctx.textBaseline = 'top';
    }

    private setupSystemCommunication(): void {
        // 设置输入系统的事件监听
        this.inputSystem.onMouseClick = (x, y) => {
            this.handleMouseClick(x, y);
        };

        this.inputSystem.onMouseMove = (x, y) => {
            this.handleMouseMove(x, y);
        };

        // 设置键盘事件监听
        this.inputSystem.onKeyDown = (key: string) => {
            this.handleKeyPress(key);
        };

        // 设置UI系统的事件监听
        this.uiSystem.onWeaponSelect = (weaponType: string) => {
            this.handleWeaponSelect(weaponType);
        };

        // 🔧 设置UI系统的建造回调
        this.uiSystem.onBuildDefenseSystem = (weaponType: string, gridX: number, gridY: number) => {
            return this.handleUIBuildRequest(weaponType, gridX, gridY);
        };

        // 🔧 设置UI系统的建造回调
        this.uiSystem.onBuildDefenseSystem = (weaponType: string, gridX: number, gridY: number) => {
            return this.handleUIBuildRequest(weaponType, gridX, gridY);
        };

        // 设置增强UI系统的事件回调
        this.enhancedUISystem.onStartGame = () => {
            this.resetGame();
            this.audioSystem.playSystemBeep();
        };

        this.enhancedUISystem.onRestartGame = () => {
            this.resetGame();
            this.audioSystem.playSystemBeep();
        };

        this.enhancedUISystem.onSettingsChange = (key: string, value: any) => {
            this.handleSettingsChange(key, value);
        };

        // 设置攻击系统的事件回调
        this.attackSystem.onMissileLaunch = (missile) => {
            this.audioSystem.playMissileLaunch();
            // 创建导弹尾迹效果
            this.visualEffectsSystem.createMissileTrail(missile.x, missile.y);
        };

        this.attackSystem.onMissileDestroyed = (missile, intercepted) => {
            if (intercepted) {
                this.gameStatistics.missilesIntercepted++;
                this.audioSystem.playIntercept();
                this.visualEffectsSystem.createInterceptExplosion(missile.x, missile.y);
            } else {
                this.audioSystem.playMissileExplosion();
                this.visualEffectsSystem.createMissileExplosion(missile.x, missile.y);
            }
        };

        // 设置防御系统的事件回调
        this.defenseSystemManager.onInterceptAttempt = (system, missile, success) => {
            if (success) {
                this.audioSystem.playIntercept();
                this.visualEffectsSystem.createInterceptExplosion(missile.x, missile.y);
            }
        };

        // 设置性能系统的质量调整回调
        this.performanceSystem.getFrameManager().onQualityChange = (quality) => {
            this.handleQualityChange(quality);
        };

        // 设置键盘快捷键（仅保留调试功能）
        this.inputSystem.onKeyDown = (key: string) => {
            this.handleKeyPress(key);
        };
    }

    private setupObjectPools(): void {
        // 创建导弹对象池
        this.performanceSystem.createPool('missiles', () => {
            return new Missile('pool_missile', 'FATEH_110', 0, 0, 0, 0);
        }, 20, 100);

        // 创建防御系统对象池
        this.performanceSystem.createPool('defenseSystems', () => {
            return new DefenseSystem('pool_defense', 'IRON_DOME', 0, 0);
        }, 10, 50);

        console.log('🏊 对象池创建完成');
    }
    
    private setupInitialDefenses(): void {
        console.log('🏗️ 防御网格已准备就绪，等待用户部署防御系统...');
        // 不再自动部署防御系统，网格保持空白状态
        // 用户可以通过点击网格来手动放置防御设施
    }

    private handleMouseClick(x: number, y: number): void {
        console.log(`🖱️ 鼠标点击: (${x}, ${y})`);
        
        // 检查是否点击在防御区域
        if (this.isInDefenseArea(x, y)) {
            this.handleDefenseAreaClick(x, y);
        }
    }

    private handleMouseMove(x: number, y: number): void {
        // 可以在这里处理鼠标移动事件，比如显示预览
    }

    private handleWeaponSelect(weaponType: string): void {
        console.log(`🔫 选择武器: ${weaponType}`);
        this.uiSystem.setSelectedWeapon(weaponType);
    }

    private isInDefenseArea(x: number, y: number): boolean {
        const defenseAreaStart = GameConfig.IRAN_AREA_WIDTH + GameConfig.SEA_AREA_WIDTH;
        return x >= defenseAreaStart && x < GameConfig.CANVAS_WIDTH && 
               y >= 0 && y < GameConfig.CANVAS_HEIGHT;
    }

    private handleDefenseAreaClick(x: number, y: number): void {
        const selectedWeapon = this.uiSystem.getSelectedWeapon();
        if (!selectedWeapon) {
            console.log('⚠️ 请先选择要建造的武器系统');
            return;
        }

        // 计算网格位置
        const defenseAreaStart = GameConfig.IRAN_AREA_WIDTH + GameConfig.SEA_AREA_WIDTH;
        const gridX = Math.floor((x - defenseAreaStart) / GameConfig.DEFENSE_GRID_SIZE);
        const gridY = Math.floor(y / GameConfig.DEFENSE_GRID_SIZE);

        console.log(`🏗️ 尝试在网格 (${gridX}, ${gridY}) 建造 ${selectedWeapon}`);

        // 尝试建造防御系统
        if (this.canBuildAt(gridX, gridY)) {
            this.buildDefenseSystem(selectedWeapon, gridX, gridY);
        } else {
            console.log('❌ 该位置无法建造');
        }
    }

    private canBuildAt(gridX: number, gridY: number): boolean {
        // 检查网格边界
        if (gridX < 0 || gridX >= GameConfig.DEFENSE_GRID_COLS ||
            gridY < 0 || gridY >= GameConfig.DEFENSE_GRID_ROWS) {
            return false;
        }

        // 检查位置是否已被占用
        return !this.entitySystem.isGridOccupied(gridX, gridY);
    }

    private buildDefenseSystem(weaponType: string, gridX: number, gridY: number): void {
        // 映射UI武器类型到配置类型
        let systemType: DefenseSystemType;
        switch (weaponType) {
            case 'iron-dome':
                systemType = 'IRON_DOME';
                break;
            case 'arrow-3':
                systemType = 'ARROW_3';
                break;
            case 'green-pine-radar':
                systemType = 'GREEN_PINE_RADAR';
                break;
            default:
                console.error(`❌ 未知的武器类型: ${weaponType}`);
                return;
        }

        // 检查资金是否足够
        const cost = GameConfig.DEFENSE_SYSTEMS[systemType].cost;
        const currentMoney = this.uiSystem.getGameState().money;
        
        if (currentMoney < cost) {
            console.log(`💰 资金不足! 需要: ${cost}, 当前: ${currentMoney}`);
            return;
        }

        // 建造防御系统
        const system = this.defenseSystemManager.buildDefenseSystem(systemType, gridX, gridY);
        
        if (system) {
            // 扣除资金
            this.uiSystem.updateMoney(currentMoney - cost);
            
            // 更新UI显示
            this.uiSystem.updateGridDisplay(gridX, gridY, true);
            
            console.log(`✅ 成功建造 ${systemType} 于网格 (${gridX}, ${gridY}), 花费: ${cost}`);
        } else {
            console.log(`❌ 建造 ${systemType} 失败`);
        }
    }

    // 🔧 新增：处理UI建造请求
    private handleUIBuildRequest(weaponType: string, gridX: number, gridY: number): boolean {
        console.log(`🔧 UI建造请求: ${weaponType} @ (${gridX}, ${gridY})`);
        
        // 检查是否可以建造
        if (!this.canBuildAt(gridX, gridY)) {
            console.log('❌ 该位置无法建造');
            return false;
        }

        // 映射UI武器类型到配置类型
        let systemType: DefenseSystemType;
        switch (weaponType) {
            case 'iron-dome':
                systemType = 'IRON_DOME';
                break;
            case 'arrow-3':
                systemType = 'ARROW_3';
                break;
            case 'green-pine-radar':
                systemType = 'GREEN_PINE_RADAR';
                break;
            default:
                console.error(`❌ 未知的武器类型: ${weaponType}`);
                return false;
        }

        // 检查资金是否足够
        const cost = GameConfig.DEFENSE_SYSTEMS[systemType].cost;
        const currentMoney = this.uiSystem.getGameState().money;
        
        if (currentMoney < cost) {
            console.log(`💰 资金不足! 需要: ${cost}, 当前: ${currentMoney}`);
            return false;
        }

        // 建造防御系统
        const system = this.defenseSystemManager.buildDefenseSystem(systemType, gridX, gridY);
        
        if (system) {
            console.log(`✅ 成功建造 ${systemType} 于网格 (${gridX}, ${gridY}), 花费: ${cost}`);
            return true;
        } else {
            console.log(`❌ 建造 ${systemType} 失败`);
            return false;
        }
    }

    private updateFPS(): void {
        this.frameCount++;
        const now = performance.now();
        
        if (now - (this.lastFrameTime - this.deltaTime) >= 1000) {
            this.fps = this.frameCount;
            this.frameCount = 0;
        }
    }

    private renderDebugInfo(): void {
        if (!GameConfig.DEBUG.SHOW_FPS) return;

        this.ctx.save();
        
        // 游戏状态面板 - 移到左侧游戏区域外
        const statusPanelX = -270; // 左侧外部位置
        const statusPanelY = 50;
        const statusPanelWidth = 250;
        const statusPanelHeight = 200;
        
        // 游戏状态面板背景
        this.ctx.fillStyle = 'rgba(0, 0, 0, 0.9)';
        this.ctx.fillRect(statusPanelX, statusPanelY, statusPanelWidth, statusPanelHeight);
        
        // 面板边框
        this.ctx.strokeStyle = '#2196F3';
        this.ctx.lineWidth = 2;
        this.ctx.strokeRect(statusPanelX, statusPanelY, statusPanelWidth, statusPanelHeight);
        
        // 面板标题
        this.ctx.fillStyle = '#2196F3';
        this.ctx.fillRect(statusPanelX, statusPanelY, statusPanelWidth, 25);
        this.ctx.fillStyle = 'white';
        this.ctx.font = 'bold 14px "Microsoft YaHei", sans-serif';
        this.ctx.textAlign = 'center';
        this.ctx.fillText('游戏状态', statusPanelX + statusPanelWidth / 2, statusPanelY + 18);
        
        // 游戏状态信息
        this.ctx.fillStyle = 'white';
        this.ctx.font = '12px monospace';
        this.ctx.textAlign = 'left';
        
        // 获取性能数据
        const performanceReport = this.performanceSystem.getPerformanceReport();
        
        const statusInfo = [
            `FPS: ${performanceReport.fps.toFixed(1)}`,
            `内存: ${performanceReport.memory.toFixed(1)}MB`,
            `实体数量: ${performanceReport.entities}`,
            `导弹数量: ${this.attackSystem.getActiveMissileCount()}`,
            `防御系统: ${this.defenseSystemManager.getDefenseSystems().length}`,
            `粒子数量: ${this.visualEffectsSystem.getActiveParticleCount()}`,
            `音效数量: ${this.audioSystem.getActiveSoundCount()}`,
            `当前波次: ${this.attackSystem.getCurrentWave()}`,
            `队列导弹: ${this.attackSystem.getQueuedMissileCount()}`,
            `自动攻击: ${this.autoAttackEnabled ? '启用' : '禁用'}`
        ];
        
        statusInfo.forEach((text, index) => {
            this.ctx.fillText(text, statusPanelX + 10, statusPanelY + 40 + index * 15);
        });
        
        this.ctx.restore();
    }

    private handleKeyPress(key: string): void {
        switch (key) {
            case 't': // 发射测试导弹
            case 'T':
                this.launchTestMissile();
                break;
                
            case 'i': // 强制测试拦截弹
            case 'I':
                this.forceTestInterceptor();
                break;
                
            case 'x': // 防御系统诊断
            case 'X':
                this.diagnosisDefenseSystem();
                break;
                
            case 'w': // 启动第1波攻击
            case 'W':
                this.startTestWave(1);
                break;
                
            case 'q': // 启动第2波攻击  
            case 'Q':
                this.startTestWave(2);
                break;
                
            case 'a': // 切换自动攻击
            case 'A':
                this.toggleAutoAttack();
                break;

            case 'd': // 切换调试模式
            case 'D':
                this.toggleDebugMode();
                break;

            case 'r': // 重置游戏
            case 'R':
                this.resetGame();
                break;

            case 'l': // 列出所有拦截弹信息
            case 'L':
                this.listAllInterceptors();
                break;

            case 'v': // 🚀 新增：可视化测试 - 强制发射拦截弹
            case 'V':
                this.visualTestInterception();
                break;

            default:
                break;
        }
    }

    private listAllInterceptors(): void {
        console.log('🔍 === 拦截弹详细调试信息 ===');
        
        // 从EntitySystem获取所有实体
        const allEntities = this.entitySystem.getAllEntities();
        console.log(`📊 EntitySystem 中总实体数: ${allEntities.length}`);
        
        // 筛选拦截弹
        const interceptors = allEntities.filter(entity => 
            entity.constructor.name === 'Interceptor'
        );
        console.log(`🚀 找到拦截弹数量: ${interceptors.length}`);
        
        interceptors.forEach((interceptor, index) => {
            console.log(`📍 拦截弹 ${index + 1}:`);
            console.log(`   ID: ${interceptor.id}`);
            console.log(`   位置: (${interceptor.x.toFixed(0)}, ${interceptor.y.toFixed(0)})`);
            console.log(`   尺寸: ${interceptor.width}x${interceptor.height}`);
            console.log(`   激活状态: ${interceptor.active}`);
        });
        
        // 检查防御系统中的拦截弹
        const defenseSystems = this.entitySystem.getEntitiesOfType(DefenseSystem);
        console.log(`🛡️ 防御系统数量: ${defenseSystems.length}`);
        
        let totalLocalInterceptors = 0;
        defenseSystems.forEach((system, index) => {
            const localInterceptors = (system as any).interceptors || [];
            totalLocalInterceptors += localInterceptors.length;
            console.log(`   防御系统 ${index + 1} 拦截弹数: ${localInterceptors.length}`);
        });
        
        console.log(`📊 防御系统内拦截弹总数: ${totalLocalInterceptors}`);
        console.log('================================');
    }

    private launchTestMissile(): void {
        console.log('🚀 发射测试导弹');
        this.attackSystem.launchTestMissile('FATEH_110');
    }
    
    private forceTestInterceptor(): void {
        console.log('🎯 强制测试拦截弹');
        
        // 首先发射一枚导弹
        this.attackSystem.launchTestMissile('FATEH_110');
        
        // 1秒后强制一个防御系统发射拦截弹
        setTimeout(() => {
            const defenseSystems = this.entitySystem.getEntitiesOfType(DefenseSystem);
            if (defenseSystems.length > 0) {
                const defenseSystem = defenseSystems[0];
                const missiles = this.entitySystem.getEntitiesOfType(Missile).filter(m => m.active);
                
                if (missiles.length > 0) {
                    const missile = missiles[0];
                    console.log(`💥 强制 ${defenseSystem.getSystemType()} 攻击 ${missile.id}`);
                    
                    // 直接调用防御系统的目标设置
                    defenseSystem.setTarget(missile);
                    
                    // 📍 额外验证：直接创建一个简单的测试拦截弹
                    this.createTestInterceptor(missile);
                } else {
                    console.log('❌ 没有找到可攻击的导弹');
                }
            } else {
                console.log('❌ 没有找到防御系统');
            }
        }, 1000);
    }

    private createTestInterceptor(target: any): void {
        console.log('🚀 创建测试拦截弹');
        
        // 创建一个非常简单的测试拦截弹
        const testInterceptor = {
            id: `test_interceptor_${Date.now()}`,
            x: 1000,
            y: 400,
            width: 20,
            height: 20,
            active: true,
            targetX: target.x,
            targetY: target.y,
            
            update: (deltaTime: number) => {
                // 简单的移动逻辑
                const dx = testInterceptor.targetX - testInterceptor.x;
                const dy = testInterceptor.targetY - testInterceptor.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                if (distance > 5) {
                    const speed = 200; // 像素/秒
                    testInterceptor.x += (dx / distance) * speed * deltaTime / 1000;
                    testInterceptor.y += (dy / distance) * speed * deltaTime / 1000;
                    
                    // 更新目标位置
                    testInterceptor.targetX = target.x;
                    testInterceptor.targetY = target.y;
                } else {
                    testInterceptor.active = false;
                    console.log('🎯 测试拦截弹到达目标');
                }
            },
            
            render: (renderSystem: any) => {
                // 非常明显的渲染
                renderSystem.renderCircleEntity(testInterceptor.x, testInterceptor.y, 15, 'red');
                renderSystem.renderCircleEntity(testInterceptor.x, testInterceptor.y, 10, 'yellow');
                renderSystem.renderCircleEntity(testInterceptor.x, testInterceptor.y, 5, 'white');
                
                // 渲染文本标识
                renderSystem.renderText(
                    'TEST',
                    testInterceptor.x - 20,
                    testInterceptor.y - 25,
                    'white',
                    'bold 12px Arial'
                );
            },
            
            destroy: () => {
                console.log('🗑️ 测试拦截弹销毁');
            }
        };
        
        // 添加到EntitySystem
        this.entitySystem.addEntity(testInterceptor as any);
        console.log(`✅ 测试拦截弹 ${testInterceptor.id} 已添加到EntitySystem`);
    }

    private startTestWave(waveNumber: number): void {
        if (this.attackSystem.isWaveInProgress()) {
            console.log('⚠️ 当前波次正在进行中');
            return;
        }

        console.log(`🌊 开始测试波次 ${waveNumber}`);
        this.attackSystem.startWave(waveNumber);
        this.uiSystem.updateWave(waveNumber);
    }

    private resetGame(): void {
        console.log('🔄 重置游戏');
        
        // 重置攻击系统
        this.attackSystem.forceEndWave();
        this.attackSystem.clearAllMissiles();
        
        // 重置防御系统
        // 注意：这里可能需要根据DefenseSystemManager的实际API调整
        
        // 重置自动攻击状态
        this.autoAttackTimer = 0;
        this.currentAutoWave = 1;
        this.hasStartedAutoAttack = false;
        this.autoAttackEnabled = true;
        
        // 重置UI
        this.uiSystem.updateWave(0);
        this.uiSystem.updateMoney(GameConfig.INITIAL_MONEY);
        
        console.log('✅ 游戏已重置');
    }

    private toggleAutoAttack(): void {
        this.autoAttackEnabled = !this.autoAttackEnabled;
        console.log(`🔄 自动攻击: ${this.autoAttackEnabled ? '启用' : '禁用'}`);
        
        if (this.autoAttackEnabled && !this.hasStartedAutoAttack) {
            this.autoAttackTimer = 0; // 重置计时器，立即开始
        }
    }

    private toggleDebugMode(): void {
        const currentDebug = GameConfig.DEBUG.ENABLED;
        GameConfig.DEBUG.ENABLED = !currentDebug;
        GameConfig.DEBUG.SHOW_FPS = !currentDebug;
        GameConfig.DEBUG.SHOW_COLLISION_BOXES = !currentDebug;
        
        console.log(`🔧 调试模式: ${GameConfig.DEBUG.ENABLED ? '启用' : '禁用'}`);
    }

    private updateGameStatusDisplay(): void {
        const activeMissiles = this.attackSystem.getActiveMissileCount();
        const defenseSystems = this.defenseSystemManager.getDefenseSystems().length;
        const currentWave = this.attackSystem.getCurrentWave();
        
        let gameState = '准备中';
        if (this.attackSystem.isWaveInProgress()) {
            gameState = '战斗中';
        } else if (currentWave > 0) {
            gameState = '待命中';
        }
        
        this.uiSystem.updateGameStatus(activeMissiles, defenseSystems, currentWave, gameState);
        
        // 计算当前游戏统计
        const missilesLaunched = this.attackSystem.getTotalMissilesLaunched();
        const missilesIntercepted = this.gameStatistics.missilesIntercepted;
        const currentScore = missilesIntercepted * 100 + currentWave * 50;
        const currentLives = Math.max(1, 3 - Math.floor((missilesLaunched - missilesIntercepted) / 5));
        
        // 更新增强UI系统的游戏统计信息
        this.enhancedUISystem.updateGameStats({
            currentWave: currentWave,
            missilesLaunched: missilesLaunched,
            missilesIntercepted: missilesIntercepted,
            money: this.uiSystem.getGameState().money,
            score: currentScore,
            lives: currentLives
        });
    }

    private updateAutoAttack(deltaTime: number): void {
        if (!this.autoAttackEnabled) return;
        
        this.autoAttackTimer += deltaTime;
        
        // 游戏开始后立即开始攻击
        if (!this.hasStartedAutoAttack && this.autoAttackTimer >= this.autoAttackDelay) {
            console.log('🎯 自动攻击序列启动 - 开始持续攻击！');
            this.launchContinuousAttacks();
            this.hasStartedAutoAttack = true;
            this.autoAttackTimer = 0;
            return;
        }
        
        // 持续发射导弹 - 减少间隔到5秒，更频繁地测试拦截
        if (this.hasStartedAutoAttack && this.autoAttackTimer >= 5000) { 
            this.launchRandomMissile();
            this.autoAttackTimer = 0;
        }
        
        // 每30秒发起一次波次攻击
        if (this.hasStartedAutoAttack && (Date.now() % 30000) < 100) {
            if (Math.random() > 0.7) { // 70% 概率发起波次攻击
                this.startTestWave(Math.floor(Math.random() * 3) + 1);
            }
        }
    }
    
    private launchContinuousAttacks(): void {
        // 立即发射几枚导弹
        const missiles = ['FATEH_110', 'QIAM_1', 'SHAHED_136'];
        missiles.forEach((type, index) => {
            setTimeout(() => {
                this.attackSystem.launchTestMissile(type as any);
            }, index * 2000);
        });
    }
    
    private launchRandomMissile(): void {
        const missileTypes = ['FATEH_110', 'SHAHAB_3', 'FATTAH_2', 'SHAHED_136', 'QIAM_1', 'ZELZAL_2'];
        const randomType = missileTypes[Math.floor(Math.random() * missileTypes.length)];
        this.attackSystem.launchTestMissile(randomType as any);
        console.log(`🚀 随机发射: ${randomType}`);
    }

    // Stage 3 新增处理方法
    private handleSettingsChange(key: string, value: any): void {
        switch (key) {
            case 'masterVolume':
                this.audioSystem.setMasterVolume(value);
                break;
            case 'sfxVolume':
                // 音效音量单独控制可以在AudioSystem中实现
                break;
            case 'particleQuality':
                // 粒子质量影响粒子系统
                this.adjustParticleQuality(value);
                break;
            default:
                console.log(`🔧 设置更改: ${key} = ${value}`);
        }
    }

    private handleQualityChange(quality: 'low' | 'medium' | 'high'): void {
        console.log(`🎯 自动质量调整: ${quality}`);
        
        switch (quality) {
            case 'low':
                this.visualEffectsSystem.clearAllParticles();
                break;
            case 'medium':
                // 中等质量设置
                break;
            case 'high':
                // 高质量设置
                break;
        }
    }

    private adjustParticleQuality(quality: number): void {
        // 根据质量设置调整粒子系统
        if (quality < 0.5) {
            // 低质量：减少粒子数量
            this.visualEffectsSystem.clearAllParticles();
        }
        console.log(`✨ 粒子质量调整为: ${quality}`);
    }

    // 公共接口
    public getCanvas(): HTMLCanvasElement {
        return this.canvas;
    }

    public getContext(): CanvasRenderingContext2D {
        return this.ctx;
    }

    public getRenderSystem(): RenderSystem {
        return this.renderSystem;
    }

    public getInputSystem(): InputSystem {
        return this.inputSystem;
    }

    public getUISystem(): UISystem {
        return this.uiSystem;
    }

    public getEntitySystem(): EntitySystem {
        return this.entitySystem;
    }

    public getFPS(): number {
        return this.fps;
    }

    public getDeltaTime(): number {
        return this.deltaTime;
    }

    // Stage 3 系统访问器
    public getVisualEffectsSystem(): VisualEffectsSystem {
        return this.visualEffectsSystem;
    }

    public getAudioSystem(): AudioSystem {
        return this.audioSystem;
    }

    public getEnhancedUISystem(): EnhancedUISystem {
        return this.enhancedUISystem;
    }

    public getPerformanceSystem(): PerformanceOptimizationSystem {
        return this.performanceSystem;
    }

    // 🚀 新增：立即创建拦截器进行可见性测试
    private createImmediateInterceptor(): void {
        console.log('🚀🚀🚀 立即创建拦截器测试');
        
        // 首先创建一个真实的测试导弹作为目标
        this.attackSystem.launchTestMissile('FATEH_110');
        
        // 等待100ms确保导弹已创建
        setTimeout(() => {
            const missiles = this.entitySystem.getEntitiesOfType(Missile).filter(m => m.active);
            if (missiles.length === 0) {
                console.error('❌ 没有找到导弹目标');
                return;
            }
            
            const targetMissile = missiles[0];
            console.log(`🎯 目标导弹: ${targetMissile.id} @ (${targetMissile.x}, ${targetMissile.y})`);
            
            // 从第一个防御系统创建拦截器
            const defenseSystems = this.entitySystem.getEntitiesOfType(DefenseSystem);
            if (defenseSystems.length > 0) {
                const defenseSystem = defenseSystems[0];
                console.log(`🛡️ 使用防御系统: ${defenseSystem.getSystemType()} @ (${defenseSystem.x}, ${defenseSystem.y})`);
                
                // 直接导入Interceptor类并创建
                import('../entities/Interceptor.js').then(({ Interceptor }) => {
                    const interceptor = new Interceptor(
                        `immediate_interceptor_${Date.now()}`,
                        defenseSystem.getSystemType(),
                        defenseSystem.x,
                        defenseSystem.y,
                        targetMissile,
                        95 // 高精度
                    );
                    
                    // 立即添加到EntitySystem
                    this.entitySystem.addEntity(interceptor);
                    console.log(`🚀🚀🚀 立即拦截器已创建: ${interceptor.id}`);
                    console.log(`   位置: (${interceptor.x}, ${interceptor.y})`);
                    console.log(`   目标: ${targetMissile.id} @ (${targetMissile.x}, ${targetMissile.y})`);
                    console.log(`   当前EntitySystem实体总数: ${this.entitySystem.getAllEntities().length}`);
                    
                    // 验证是否在EntitySystem中
                    const found = this.entitySystem.getEntity(interceptor.id);
                    console.log(`🔍 在EntitySystem中找到: ${found ? '是' : '否'}`);
                    
                    // 强制渲染验证
                    console.log(`✅ 拦截器活跃状态: ${interceptor.active}`);
                }).catch(error => {
                    console.error('❌ 导入Interceptor类失败:', error);
                });
            } else {
                console.error('❌ 没有找到防御系统！');
            }
        }, 100);
    }

    // 🚀 新增：可视化测试拦截效果
    private visualTestInterception(): void {
        console.log('🎭 === 可视化拦截测试 ===');
        
        // 1. 发射多枚导弹
        const missileTypes = ['FATEH_110', 'SHAHAB_3', 'QIAM_1'];
        missileTypes.forEach((type, index) => {
            setTimeout(() => {
                this.attackSystem.launchTestMissile(type as any);
                console.log(`🚀 发射测试导弹: ${type}`);
            }, index * 1000);
        });
        
        // 2. 强制所有防御系统准备拦截
        setTimeout(() => {
            const defenseSystems = this.entitySystem.getEntitiesOfType(DefenseSystem);
            console.log(`🛡️ 找到 ${defenseSystems.length} 个防御系统`);
            
            defenseSystems.forEach((system, index) => {
                console.log(`🎯 防御系统 ${index + 1}: ${system.getSystemType()} @ (${system.x}, ${system.y})`);
                
                // 强制开启调试模式显示射程
                GameConfig.DEBUG.ENABLED = true;
                GameConfig.DEBUG.SHOW_COLLISION_BOXES = true;
            });
        }, 3000);
        
        // 3. 输出测试说明
        setTimeout(() => {
            console.log('📋 可视化测试说明:');
            console.log('   🔵 蓝色虚线圈 = 防御系统射程');
            console.log('   🟢 绿色光束 = 铁穹拦截弹');
            console.log('   🔵 蓝色光束 = 箭-3拦截弹');
            console.log('   🔥 红色脉冲 = 发射状态');
            console.log('   ⚡ 白色连线 = 发射光束');
            console.log('   📊 右上角数字 = 活跃拦截弹数量');
        }, 5000);
    }

    // 🔧 新增：防御系统诊断
    private diagnosisDefenseSystem(): void {
        console.log('🔍🔍🔍 === 防御系统完整诊断 ===');
        
        // 1. 检查防御系统状态
        const defenseSystems = this.entitySystem.getEntitiesOfType(DefenseSystem);
        console.log(`🛡️ 总防御系统数量: ${defenseSystems.length}`);
        
        defenseSystems.forEach((system, index) => {
            console.log(`🛡️ 防御系统 ${index + 1}:`);
            console.log(`   类型: ${system.getSystemType()}`);
            console.log(`   位置: (${system.x.toFixed(0)}, ${system.y.toFixed(0)})`);
            console.log(`   状态: ${(system as any).state}`);
            console.log(`   射程: ${(system as any).range}px`);
            console.log(`   激活: ${system.active}`);
            console.log(`   冷却计时器: ${(system as any).cooldownTimer}ms`);
            console.log(`   当前目标: ${(system as any).currentTarget?.id || '无'}`);
        });
        
        // 2. 检查导弹状态
        const missiles = this.entitySystem.getEntitiesOfType(Missile).filter(m => m.active);
        console.log(`🚀 活跃导弹数量: ${missiles.length}`);
        
        missiles.forEach((missile, index) => {
            console.log(`🚀 导弹 ${index + 1}:`);
            console.log(`   ID: ${missile.id}`);
            console.log(`   位置: (${missile.x.toFixed(0)}, ${missile.y.toFixed(0)})`);
            console.log(`   目标: (${(missile as any).targetX.toFixed(0)}, ${(missile as any).targetY.toFixed(0)})`);
            console.log(`   激活: ${missile.active}`);
            
            // 计算每个导弹与防御系统的距离
            defenseSystems.forEach((system, sysIndex) => {
                const distance = Math.sqrt(
                    Math.pow(missile.x - system.x, 2) + 
                    Math.pow(missile.y - system.y, 2)
                );
                const inRange = distance <= (system as any).range;
                console.log(`     距离防御系统${sysIndex + 1}: ${distance.toFixed(0)}px ${inRange ? '✅射程内' : '❌射程外'}`);
            });
        });
        
        // 3. 检查拦截器
        const interceptors = this.entitySystem.getAllEntities().filter(e => e.constructor.name === 'Interceptor');
        console.log(`🎯 拦截器数量: ${interceptors.length}`);
        
        interceptors.forEach((interceptor, index) => {
            console.log(`🎯 拦截器 ${index + 1}:`);
            console.log(`   ID: ${interceptor.id}`);
            console.log(`   位置: (${interceptor.x.toFixed(0)}, ${interceptor.y.toFixed(0)})`);
            console.log(`   激活: ${interceptor.active}`);
            console.log(`   目标: ${(interceptor as any).target?.id || '无'}`);
        });
        
        // 4. 模拟防御逻辑
        if (missiles.length > 0 && defenseSystems.length > 0) {
            console.log('🔧 手动触发防御逻辑测试...');
            defenseSystems.forEach((system) => {
                if ((system as any).state === 'scanning' || (system as any).state === 'idle') {
                    console.log(`🔧 强制触发 ${system.getSystemType()} 的扫描`);
                    // 直接调用扫描方法
                    (system as any).scanForTargets();
                }
            });
        }
    }
}
